package com.app.newcsc.fragment.orderdetail;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;

import com.app.newcsc.BR;
import com.app.newcsc.R;
import com.app.newcsc.data.DemoRepository;
import com.app.newcsc.entity.DemoEntity;
import com.app.newcsc.entity.Message;
import com.app.newcsc.entity.TransactionOrderEntity;
import com.app.newcsc.entity.UploadFileEntity;
import com.app.newcsc.fragment.my.paytype.PayTypeItemViewModel;
import com.app.newcsc.http.response.ApiException;
import com.app.newcsc.utils.Compressor;
import com.app.newcsc.utils.TextUtil;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @author: woking
 * @date: 2021/6/17
 * @description：
 */
public class OrderDetailViewModel extends BaseViewModel<DemoRepository> {
    private int page = 1;

    public SingleLiveEvent<PayTypeItemViewModel> deleteItemLiveData = new SingleLiveEvent<>();
    public SingleLiveEvent<TransactionOrderEntity> mTransactionOrderEntity = new SingleLiveEvent<>();
    public SingleLiveEvent<TransactionOrderEntity> mTransactionOrderGuaDanEntity = new SingleLiveEvent<>();
    public SingleLiveEvent<UploadFileEntity> mUploadFileEntity = new SingleLiveEvent<>();
    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();
    }

    public OrderDetailViewModel(@NonNull Application application, DemoRepository repository) {
        super(application, repository);
    }

    //给RecyclerView添加ObservableList
    public ObservableList<PayTypeItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<PayTypeItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_my_paytype_item);
    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            requestNetWork(false);
        }
    });

    public void onRefresh()
    {
        requestNetWork(false);
    }

    public void onLoadMore()
    {
        requestNetWork(true);
    }

    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            onLoadMore();
        }
    });

    /**
     * 网络请求方法，在ViewModel中调用Model层，通过Okhttp+Retrofit+RxJava发起请求
     */
    public void requestNetWork(boolean isLoadMore) {
        Log.e("TAG","====type======requestNetWork========isBuy=====");
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
//        http://csc.chaishows.com/api/otc/plan/list?type=1&lang=zh-cn HTTP/1.1 page=1&keyword=&num_zone=1-10
        if(!isLoadMore)
        {
            page = 1;
        }
        else {
            page++;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("lang","zh-cn");
//        map.put("page",page+"");
        model.payAccountList(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<DemoEntity>>() {
                    @Override
                    public void onNext(BaseResponse<DemoEntity> response) {
//                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //清除列表
                            observableList.clear();
                        }
                        //请求成功
                        if (response.getCode() == 1) {
//                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
//                                PayTypeItemViewModel itemViewModel = new PayTypeItemViewModel(PayTypeViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
                            ToastUtils.showShort("数据错误");
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
                        dismissDialog();
                        //请求刷新完成收回
                        uc.finishRefreshing.call();
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
                        dismissDialog();
                        if(!isLoadMore)
                        {
                            //请求刷新完成收回
                            uc.finishRefreshing.call();
                        }
                        else
                        {
                            uc.finishLoadmore.call();
                        }
                    }
                });
    }

    public void otcBuyShowOrder(String id)
    {
        model.otcBuyShowOrder(id)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<TransactionOrderEntity>>() {
                    @Override
                    public void onNext(BaseResponse<TransactionOrderEntity> response) {
                        Log.e("TAG","============otcBuyShowOrder=====onNext========");
                        if(null != response && null != response.getData())
                        {
                            mTransactionOrderEntity.setValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============otcBuyShowOrder=====onError========"+throwable.getMessage());
                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
//                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============otcBuyShowOrder=====onComplete========");
                        dismissDialog();
                    }
                });
    }

    /**
     * 挂单详情
     * @param id
     */
    public void otcPlanOrderDetail(String id)
    {
        model.otcPlanOrderDetail(id)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<TransactionOrderEntity>>() {
                    @Override
                    public void onNext(BaseResponse<TransactionOrderEntity> response) {
                        Log.e("TAG","============otcPlanOrderDetail=====onNext========");
                        if(null != response && null != response.getData())
                        {
                            mTransactionOrderGuaDanEntity.setValue(response.getData());
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============otcPlanOrderDetail=====onError========"+throwable.getMessage());
                        dismissDialog();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
//                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============otcPlanOrderDetail=====onComplete========");
                        dismissDialog();
                    }
                });
    }


    /**
     * 卖家 确认订单
     * @param id
     */
    public void otcBuyConfirm(String id,String payment_password)
    {
        model.otcBuyConfirm(id, payment_password)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============otcBuyConfirm=====onNext========");
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        dismissDialog();
                        Log.e("TAG","============otcBuyConfirm=====onError========"+throwable.getMessage());
                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            ToastUtils.showShortSafe(msg);
                            if(!TextUtil.isEmpty(msg) && msg.contains("成功"))
                            {
                                finish();
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        dismissDialog();
                        Log.e("TAG","============otcBuyConfirm=====onComplete========");
                        finish();
                    }
                });
    }

    /**
     * 买家 确认上传
     * @param id
     */
    public void otcBuySubmit(String id,String pay_id,String image,String payment_password)
    {
        model.otcBuySubmit(id, pay_id, image,payment_password)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============otcBuySubmit=====onNext========");
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        dismissDialog();
                        Log.e("TAG","============otcBuySubmit=====onError========"+throwable.getMessage());
                        if (throwable instanceof ResponseThrowable) {
                             ToastUtils.showShortSafe(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            if(!TextUtil.isEmpty(msg) && msg.contains("成功"))
                            {
                                RxBus.getDefault().post(new Message("upload_finish",""));
                                finish();
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        RxBus.getDefault().post(new Message("upload_finish",""));
                        dismissDialog();
                        Log.e("TAG","============otcBuySubmit=====onComplete========");
                        finish();
                    }
                });
    }

    /**
     * 仲裁
     * @param id
     */
    public void otcBuyAppeal(String id,String image,String content)
    {
        model.otcBuyAppeal(id, image,content)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody response) {
                        Log.e("TAG","============otcBuyAppeal=====onNext========");
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        dismissDialog();
                        Log.e("TAG","============otcBuyAppeal=====onError========"+throwable.getMessage());
                        if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShortSafe(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            if(!TextUtil.isEmpty(msg) && msg.contains("成功"))
                            {
                                RxBus.getDefault().post(new Message("upload_finish",""));
                                finish();
                            }
                        }
                    }
                    @Override
                    public void onComplete() {
                        RxBus.getDefault().post(new Message("upload_finish",""));
                        dismissDialog();
                        finish();
                        Log.e("TAG","============otcBuyAppeal=====onComplete========");
                    }
                });
    }
    public void uploadFiles(String imgpath)
    {
        File file = new File(imgpath);
        File compressedImage = null;
        if (file.exists()) {
            //压缩文件
            try {
                compressedImage = new Compressor(getApplication()).compressToFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (compressedImage == null) {
                compressedImage = file;
            }

            RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), compressedImage);
            MultipartBody.Part part = MultipartBody.Part
//                                .createFormData("key","AAAAA.png")
                    .createFormData("file", file.getName(), requestBody);

            model.uploadFile("image", part)
                    .compose(RxUtils.schedulersTransformer()) //线程调度
                    .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                    .doOnSubscribe(this)//请求与ViewModel周期同步
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(Disposable disposable) throws Exception {
                            showDialog("正在请求...");
                        }
                    })
                    .subscribe(new DisposableObserver<BaseResponse<UploadFileEntity>>() {
                        @Override
                        public void onNext(BaseResponse<UploadFileEntity> response) {
                            Log.e("TAG","==============uploadFiles=======onNext======");

                            if(response != null && response.getData() != null)
                            {
                                Log.e("TAG","==============uploadFiles=======onNext===11111==="+response.getData().url);
                                mUploadFileEntity.postValue(response.getData());
                            }
                        }
                        @Override
                        public void onError(Throwable throwable) {
                            Log.e("TAG","==============uploadFiles=======onError======"+throwable.getMessage());
                            //关闭对话框
                            dismissDialog();
                            if(throwable.getMessage().contains("timeout"))
                            {
                                ToastUtils.showShort("上传失败");
                                return;
                            }
                            if (throwable instanceof ResponseThrowable) {
                                ToastUtils.showShort(ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody));
                            }
                        }
                        @Override
                        public void onComplete() {
                            Log.e("TAG","==============uploadFiles=====onComplete========");
                            ToastUtils.showShort("上传成功");
                            //关闭对话框
                            dismissDialog();
                        }
                    });
        }
    }
    /**
     * 删除条目
     *
     * @param netWorkItemViewModel
     */
    public void deleteItem(PayTypeItemViewModel netWorkItemViewModel) {
        //点击确定，在 observableList 绑定中删除，界面立即刷新
        observableList.remove(netWorkItemViewModel);
    }

    /**
     * 获取条目下标
     *
     * @param netWorkItemViewModel
     * @return
     */
    public int getItemPosition(PayTypeItemViewModel netWorkItemViewModel) {
        return observableList.indexOf(netWorkItemViewModel);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}